import md5 from 'js-md5';
import {
	base64encode
} from "strman"
import store from "../../store"
import {
	getEncrypter
} from "./encrypter.js"

export const requestData = {
	// 商品详情页面的分享需要换正式地址
	url: "http://www.bobei.shop", //s正式 
	// url: "http://www.hthy.top", // 测试
	enc: false,
	appKey: "d66c3086e1b746aeadc2de1570f24060",
	aesKey: "jY1U5999NDRhOGVlMTg0M2EyMGIzMTNlMWRjZTkyNmEzYWI5NDk=5Odpz5Ep",
}

export const {
	aesDecrypt,
	aesEncrypt
} = getEncrypter(requestData.aesKey);

function errTips(message, tips = true) {
	if (tips) {
		setTimeout(() => {
			uni.showToast({
				title: message,
				icon: "none",
				duration: 1500,
			});
		}, 0)

	}
}

function sortObj(obj) {
	let keysArr = Object.keys(obj).sort();
	let sortObj = {};
	for (let i in keysArr) {
		sortObj[keysArr[i]] = obj[keysArr[i]];
	}
	return sortObj;
}
/**
 * 将传入的对象以【key】=【value】&【key】=【value】的形式拼接为字符串
 * @param {Object} obj 需要被拼接的对象
 * @return {String}
 */
function serializeObject(obj) {
	let str = [];
	for (let p in obj) {
		str.push(p + "=" + encodeURIComponent(obj[p]));
	}
	return str.join("&");
}

/**
 * 生成接口签名验证字符串
 * @param {Object} request 请求数据对象
 * @return {String}
 */
function sign(request) {
	// 参数排序
	request = sortObj(request)
	// 临时字符串
	let tempString = serializeObject(request)
	// 加密
	let result = md5(base64encode(`${requestData.appKey}${tempString}${requestData.appKey}`)).toLowerCase()
	return result;
}

let loadingCount = 0;
export function startLoading() {
	if (loadingCount++ === 0) {
		uni.showLoading({
			title: "加载中",
			mask: true,
		})
	}
	loadingCount;
}

export function stopLoading() {
	if (loadingCount-- === 1) {
		uni.hideLoading();
	}
}

async function requestSuccessHandler(opt, response) {
	let data = typeof response.data === "string" ? JSON.parse(response.data) : response.data
	data = requestData.enc ? aesDecrypt(data.encryptedData) : data;
	if (data.code === 0) {
		return data.data || data
	} else {
		// console.log("error -> ", data);
		switch (data.code) {
			case 4700:
				// errTips("用户登录失效，请重新登录")
				const pages = getCurrentPages()
				if (pages.length === 0 || pages[pages.length - 1].route !==
					"/pages/login/index") {
					store.commit("SET_USER_TOKEN")
					uni.reLaunch({
						url: "/pages/login/index"
					})
				}
				break;
			case 4500:
				errTips(data.message, opt.tips);
				break;
			case 4800:
				errTips(data.message, opt.tips);
				break;
			case 4810:
				errTips(data.message, opt.tips);
				break;
			default:
				errTips('网络异常，请稍后..', opt.tips);
				break;
		}
		throw data;
	}
}

/**
 * post请求
 * @param { Object } opt 请求配置项
 * @return { Promise } 异步的请求结果
 */
export function post(opt) {
	return new Promise((resolve, reject) => {
		if (opt.loading === undefined) {
			opt.loading = true;
		}

		// if (opt.loading) {
		// 	startLoading();
		// }

		let reqData = {
			source: 'web',
			version: 'v1',
			module: opt.module,
			interface: opt.interface,
			timestamp: Math.floor(new Date().getTime() / 1000),
		}
		if (requestData.appKey) {
			reqData.sign = sign(reqData);
		}
		reqData.data = opt.data;

		if (requestData.enc) {
			reqData = {
				encryptedData: aesEncrypt(reqData),
			}
		}

		uni.request({
			url: opt.url ? `${requestData.url}${opt.url}` : `${requestData.url}/portal`,
			timeout: 10000,
			data: reqData,
			method: "POST",
			dataType: "JSON",
			header: {
				Authorization: `Bearer ${uni.getStorageSync('token')}`
			},
			success(response) {
				requestSuccessHandler(opt, response).then(resolve).catch(reject);
			},
			fail(err) {
				// console.log("fail -> ", err);
				err.message = "+请求出现异常，请联系管理员或稍后再试";
				errTips(err.message, opt.tips);
				reject(err);
			},
			complete() {
				opt.loading && stopLoading();
			}
		})
	})
}

export function upload(filePath) {
	return new Promise((resolve, reject) => {
		startLoading();
		// // console.log("filePath",filePath);
		uni.uploadFile({
			url: `${requestData.url}/upload`,
			header: {
				Authorization: `Bearer ${uni.getStorageSync('token')}`
			},
			name: "file",
			timeout: 10000,
			filePath: filePath.data.filePath,
			success(response) {
				requestSuccessHandler({
					tips: true,
					loading: true,
				}, response).then(res => {
					// // console.log(res);
					resolve(res)
				}).catch(reject);
			},
			fail(err) {
				// console.log("fail -> ", err);
				err.message = "请求出现异常，请联系管理员或稍后再试";
				errTips(err.message, opt.tips);
				reject(err);
			},
			complete: stopLoading,
		})
	})
}
